package com.szty.lib_pen.oss

import android.graphics.Bitmap
import com.alibaba.sdk.android.oss.ClientConfiguration
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.common.OSSLog
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider
import com.alibaba.sdk.android.oss.common.auth.OSSCustomSignerCredentialProvider
import com.alibaba.sdk.android.oss.common.utils.OSSUtils
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.sjh.lib_app.AppApplication
import com.sjh.lib_app.AppConfig
import com.sjh.lib_app.bean.Request
import com.sjh.lib_app.bean.SignatureData
import com.sjh.lib_app.net.NetConfig
import com.sjh.baseui.picture.PictureUtils.getBitmapByte
import com.sjh.baseutils.loge
import com.sjh.baseutils.logi
import com.sjh.baseutils.toast
import com.sjh.net.Method
import com.sjh.net.request
import java.io.File
import java.io.FileInputStream


/**
 *    author : SunJH
 *    date   : 2021/5/17 0017
 *    desc   :
 */
class OssHelper {
    var signature = ""

    /**
     * 自动更新签名参数逻辑
     * 调用获取签名方法时，验证时间是否过期，如果过期，再次申请签名参数
     */
    var credentialProvider: OSSCredentialProvider = object : OSSCustomSignerCredentialProvider() {
        override fun signContent(content: String?): String {
            return OSSUtils.sign(
                "LTAI5tAkt9y2PnfPdfxyNvgs",
                "DtVgB5sOg7X77LEV3V6D81aJKoJson",
                content
            )
        }
    }
    private val conf = ClientConfiguration().apply {
        connectionTimeout = 15*1000     //连接超时
        socketTimeout = 15*1000         //socket超时
        maxConcurrentRequest = 5        // 最大并发请求数
        maxErrorRetry = 2               //失败后最大重试次数
    }
    private var oss = OSSClient(
        AppApplication.application,
        AppConfig.getEndPoint(),
        credentialProvider,
        conf
    )

    companion object {
        private lateinit var ossHelper: OssHelper

        /**
         * 获取实例
         * @return AppUpDateManage
         */
        fun getInstance(): OssHelper {
            ossHelper = OssHelper()
            return ossHelper
        }
    }

    init {
        if (AppConfig.isShowLog()) {
            OSSLog.enableLog()
        }
        //现在走自签名，不获取服务器签名参数
//        getSignatureInfo()

    }

    private fun getSignatureInfo() {
        request<Request<SignatureData>>(preBlock = { NetConfig.appConfig(this) }, options = {
            method = Method.GET
        }) {
            url = "/api/oss/signature"
            params = {
                "type" to "android-image"
            }
            onError = {
                it.printStackTrace()
            }
            onResult = { s: String, request: Request<SignatureData>, b: Boolean, i: Int ->
                request.dispose {
                    it?.let { signatureData ->
                        signature = signatureData.signature
                        oss = OSSClient(
                            AppApplication.application,
                            AppConfig.getEndPoint(),
                            credentialProvider
                        )
                    }
                }
            }
        }
    }

    fun upLoadFile(filePath: String,questionId:String,process:(Int)->Unit,upLoadResult: (Boolean) -> Unit){
        val putObjectRequest =
            PutObjectRequest(AppConfig.getBuctet(), "jyzs/video/${questionId}_${File(filePath).name}", filePath)
        putObjectRequest.setProgressCallback { request, currentSize, totalSize ->
            totalSize.logi("totalSize")
            currentSize.logi("currentSize")
            process.invoke(((currentSize.toFloat()/totalSize.toFloat())*100).toInt())
        }
        oss.asyncPutObject(putObjectRequest, object : OSSCompletedCallback<PutObjectRequest, PutObjectResult> {
            override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult?) {
                upLoadResult.invoke(true)
            }
            override fun onFailure(
                request: PutObjectRequest?,
                clientException: ClientException?,
                serviceException: ServiceException?
            ) {
                "上传失败".loge()
                clientException?.printStackTrace()
                serviceException?.printStackTrace()
                upLoadResult.invoke(false)
            }
        })
    }
    fun upLoadImg(
        img: Bitmap,
        fileName: String,
        upLoadResult: (Boolean, String?) -> Unit
    ) {
        val bitmapArray = getBitmapByte(img)
        val put = PutObjectRequest(
            AppConfig.getBuctet(),
            "app/correct/${fileName}.png",
            bitmapArray
        )
        oss.asyncPutObject(put, object : OSSCompletedCallback<PutObjectRequest, PutObjectResult> {
            override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult?) {
                upLoadResult.invoke(true, request?.objectKey)
            }

            override fun onFailure(
                request: PutObjectRequest?,
                clientException: ClientException?,
                serviceException: ServiceException?
            ) {
                clientException?.printStackTrace()
                serviceException?.printStackTrace()
                upLoadResult.invoke(false, request?.objectKey)

            }
        })
    }

}